import React, { useState, useEffect } from 'react';
import Alert from '@material-ui/lab/Alert';
import { urlGet, urlMd, obj_str, IkFind, IkFindDate, IkSelect, is_empty, CkValue, IkInput, useForm, useCmd, Btn, WaitUmd,
    PanelTitle, Ret, obj_empty, useCheck } from '../../nui';
import { loc } from '../../local';

/* lst: [
 *     {sn: "xx", name: "xx", ck: ckfunc}
 * ]
*/
const HandBase = ({ title, hreturn, cur, lst, hedit, hadd, init, opt, info=null }) => {
    const [ck, setCk] = useState({});
    const [ckdes, setCkdes] = useState({});
    const [value, setValue] = useState();
    const form = useForm(setValue);
    const [open, setOpen, hcheck] = useCheck();
    const umd = useCmd(null, "hand");

    useEffect(() => {
        if (!obj_empty(init)) {
            setValue(init);
        }

        if (is_empty(lst)) {
            return;
        }

        const tmp_ck = {};
        const tmp_ckdes = {};

        lst.forEach(d => {
            if (d.ck) {
                tmp_ck[d.sn] = (v) => d.ck(v, d.sn);
                tmp_ckdes[d.sn] = d.name;
            }
        });

        setCk(tmp_ck);
        setCkdes(tmp_ckdes);
    }, [cur, lst, init]);

    const hdone = () => {
        if (!form.hcheck(ck, value)) {
            return;
        }

        umd.startWait();

        if (obj_empty(cur)) {
            hadd(value, umd);
            return;
        }

        hedit(value, umd);
    };

    const Right = () => {
        const title = obj_empty(cur) ? loc("tj") : loc("xg");
        return (
            <div className="inline-flex">
                <Btn name="done" className="mr-4" color="green" hcmd={() => hcheck(value, ckdes, hdone)}>{title}</Btn>
                <Ret hcmd={hreturn}/>
            </div>
        );
    };

    const getCtl = (d) => {
        if (d.ctl === "IkFind") {
            return <IkFind key={d.sn} className="mr-4" name={d.sn} label={d.name} form={form} value={value} lst={d.lst}/>;
        }
        else if (d.ctl === "IkFindDate") {
            const tp = d.tp ? d.tp : "datetime";
            return <IkFindDate key={d.sn} className="mr-4" name={d.sn} name_s={d.start} name_e={d.end} label={d.name} form={form} value={value} type={tp}/>
        }
        else if (d.ctl === "IkSelect") {
            return <IkSelect key={d.sn} className="mr-4 mt-2" name={d.sn} label={d.name} form={form} value={value} lst={d.lst}/>;
        }

        return <IkInput key={d.sn} label={d.name} name={d.sn} form={form} value={value} className="mr-4"/>;
    };

    const getView = () => {
        if (is_empty(lst)) {
            if (info) {
                return <Alert severity="info" className="text-1xl my-4">{info}</Alert>
            }

            return null;
        }

        return lst.map(d => getCtl(d));
    };

    const getOpt = () => {
        if (is_empty(opt)) {
            return null;
        }

        return (
            <div>
                <Alert severity="info" className="text-1xl my-4">{loc("xtx")}</Alert>
                <div className="mt-4 flex flex-row flex-wrap">
                    {opt.map(d => getCtl(d))}
                </div>
            </div>
        );
    };

    return (
        <div className="w-full">
            <PanelTitle left={title} right={<Right/>}/>
            <div className="ml-4">
                <div className="mt-4 flex flex-row flex-wrap">
                    {getView()}
                </div>
                {getOpt()}
            </div>
            <WaitUmd umd={umd}/>
            <CkValue setOpen={setOpen} open={open} value={value} des={ckdes} setValue={setValue} hcmd={hdone}/>
        </div>
    );
};

const hand_edit = (cur, data, umd, hreturn) => {
    const cmd = {
        m: [{
            u: obj_str(cur, "uid"),
            v: data,
        }]
    };

    urlMd(null, cmd,
        r => {
            umd.endWait();
            hreturn();
        },
        e => umd.setWrong(loc("xgsb")));
};

const hand_add = (uid, sn, data, umd, hreturn, label, nd="node") => {
    urlGet(null,
        {
            n: nd,
            obj: "uid",
            opt: {and: [{eq: "sn", v: sn}]}
        },
        r => umd.setWrong(`${label}${loc("yjcz")}`),
        e => {
            urlMd(null,
                {
                    a: [{
                        u: uid,
                        n: nd,
                        v: [data]
                    }]
                },
                r => {
                    umd.endWait();
                    hreturn();
                },
                e => umd.setWrong(loc("tjsb")));
        }, uid
    );
};

const MsgInfo = ({ msg, type="info" }) => <Alert severity={type} className="text-1xl my-4">{msg}</Alert>;

export {MsgInfo, hand_add, hand_edit, HandBase};
